<template>
  <div class="createPost-container">
    <el-form ref="popularForm" :model="popularForm" :rules="rules" class="form-container">

      <sticky :z-index="10" :class-name="'sub-navbar '+popularForm.status">
        <CommentDropdown v-model="popularForm.comment_disabled" />
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          保存并发布
        </el-button>
        <el-button v-loading="loading" type="warning" @click="draftForm">
          保存
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>

          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="popularForm.title" :maxlength="100" name="name" required>
                标题
              </MDinput>
            </el-form-item>
            <el-form-item style="margin-bottom: 40px;" prop="catalogue_identity">
              <el-select v-model="popularForm.catalogue_identity" placeholder="请选择">
                <el-option
                  v-for="item in catalogeOptions"
                  :key="item.identity"
                  :label="item.title"
                  :value="item.identity"
                />
              </el-select>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>

                <el-col :span="10">
                  <el-form-item label-width="120px" label="上线时间:" class="postInfo-container-item">
                    <el-date-picker  v-model="popularForm.publish_time" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="Select date and time" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="摘要:">
          <el-input v-model="popularForm.description" :rows="1" type="textarea" class="article-textarea" autosize placeholder="Please enter the content" />
          <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}words</span>
        </el-form-item>

        <el-form-item prop="正文" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="popularForm.content" :height="400" />
        </el-form-item>

        <el-form-item prop="avatar" style="margin-bottom: 30px;">
          <Upload v-model="popularForm.avatar" />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload/SingleImage3'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import { validURL } from '@/utils/validate'
import { saveComplaint, getComplaint } from '@/api/knowledge/popular'
import { getCataloguesAvabile } from '@/api/knowledge/catalogue'
import { searchUser } from '@/api/search/search'
import { CommentDropdown } from './dropdown'

const defaultForm = {
  status: { value: 1, label: '草稿' },
  title: '', // 文章题目
  content: '', // 文章内容
  description: '', // 文章摘要
  source_uri: '', // 文章外链
  avatar: '', // 文章图片
  publish_time: undefined, // 前台展示时间
  id: undefined,
  platforms: ['a-platform'],
  comment_disabled: false,
  importance: 0
}

export default {
  name: 'ArticleDetail',
  components: { Tinymce, MDinput, Upload, Sticky, CommentDropdown },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    const validateSourceUri = (rule, value, callback) => {
      if (value) {
        if (validURL(value)) {
          callback()
        } else {
          this.$message({
            message: '外链url填写不正确',
            type: 'error'
          })
          callback(new Error('外链url填写不正确'))
        }
      } else {
        callback()
      }
    }
    return {
      popularForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      catalogeOptions: [],
      rules: {
        avatar: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }],
        source_uri: [{ validator: validateSourceUri, trigger: 'blur' }]
      },
      tempRoute: {}
    }
  },
  computed: {
    contentShortLength() {
      return this.popularForm.description.length
    },
    displayTime: {
      // set and get is useful when the data
      // returned by the back end api is different from the front end
      // back end return => "2013-06-25 06:59:25"
      // front end need timestamp => 1372114765000
      get() {
        return (+new Date(this.popularForm.publish_time))
      },
      set(val) {
        this.popularForm.publish_time = new Date(val)
      }
    }
  },
  created() {
    this.getCatalogueList()
    let popularId = this.$route.query && this.$route.query.popularId
    if (popularId !== undefined) {
      popularId = parseInt(popularId)
      if (!isNaN(popularId)) {
        this.listLoading = true
        const formData = {
          'popularId': popularId
        }
        getComplaint(formData).then(response => {
          if (response.status === 200) {
            this.popularForm = response.data

            // set tagsview title
            this.setTagsViewTitle()

            // set page title
            this.setPageTitle()
          } else {
            this.$message({
              message: response.msg,
              type: 'error'
            })
          }
        })
      }
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    setTagsViewTitle() {
      const title = 'Edit Article'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.popularForm.id}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = 'Edit Article'
      document.title = `${title} - ${this.popularForm.id}`
    },
    getCatalogueList() {
      getCataloguesAvabile().then(response => {
        if (response.status === 200) {
          this.catalogeOptions = response.data.list
        }
      })
    },
    submitForm() {
      console.log(this.popularForm)

      this.$refs.popularForm.validate(valid => {
        if (valid) {
          this.loading = true
          const _popularForm = this.popularForm
          _popularForm.status = 6
          _popularForm.popularId = _popularForm.identity
          saveComplaint(_popularForm).then(response => {
            if (response.status === 200) {
              this.$message({
                message: '保存成功',
                type: 'success',
                showClose: true,
                duration: 1000
              })
              this.popularForm.identity = response.data.popularId
              this.loading = false
              this.$router.push({ path: 'popular' })
            } else {
              this.$message({
                message: response.msg,
                type: 'error'
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    draftForm() {
      if (this.popularForm.content.length === 0 || this.popularForm.title.length === 0) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        })
        return
      }
      const _popularForm = this.popularForm
      _popularForm.status = 1
      _popularForm.popularId = _popularForm.identity
      saveComplaint(_popularForm).then(response => {
        if (response.status === 200) {
          this.$message({
            message: '保存成功',
            type: 'success',
            showClose: true,
            duration: 1000
          })
          this.popularForm.identity = response.data.popularId
        } else {
          this.$message({
            message: response.msg,
            type: 'error'
          })
        }
      })
    },
    getRemoteUserList(query) {
      searchUser(query).then(response => {
        if (!response.data.items) return
        this.userListOptions = response.data.items.map(v => v.name)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
